package com.humh.order.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.humh.order.common.CommonResult;
import com.humh.order.common.HttpClientUtils;
import com.humh.order.controller.req.OrderReq;
import com.humh.order.controller.req.StockReq;
import com.humh.order.controller.res.OrderRes;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>订单接口</p>
 * Create by hgx61 at 2024/10/18
 */

@RestController
@RequestMapping("/orders")
public class OrderController {

  private static final String URL_CHECK_TOKEN = "http://localhost:8082/tokens/checkToken";  // 验证token 是否存在
  private static final String URL_STOCKS = "http://localhost:8085/stocks";  // 扣减库存接口


  /**
   * 创建订单
   *
   * @param orderReq
   * @return
   */
  @PutMapping
  public CommonResult<OrderRes> createOrder(@RequestHeader("token") String token, @RequestBody OrderReq orderReq)
      throws Exception {

    Map<String, String> params = new HashMap<>();
    params.put("token", token);

    // 访问certification-service 的TokenController.verifyToken() 验证token 是否存在,存在则继续处理创建订单的请求，反之则返回错误信息
    JsonNode tokenJsonNode = HttpClientUtils.sendGet(URL_CHECK_TOKEN, null, params);
    // 验证token
    if (!CommonResult.isSuccess(tokenJsonNode.get("code").asInt())) { // token 不存在
      return CommonResult.error(tokenJsonNode.get("code").asInt(), tokenJsonNode.get("msg").asText());
    }

    StockReq stockReq = new StockReq();
    stockReq.setProductCode(orderReq.getProductCode());
    stockReq.setNum(orderReq.getNum());
    Map<String, String> headers = new HashMap<>(); // 请求头
    headers.put("token", token);  // 将 token 放入请求头

    // 访问stock-servic 服务的 StockController.deductionOfInventory() 来扣减库存
    JsonNode jsonNode = HttpClientUtils.sendPost(URL_STOCKS, headers, stockReq);
    if (jsonNode.get("code").asInt() == 100) {
      System.out.println("扣减库存成功");
    } else {
      return CommonResult.error(jsonNode.get("code").asInt(), jsonNode.get("msg").asText());
    }

    // 模拟下单
    OrderRes orderRes = new OrderRes();
    orderRes.setOrderId(orderReq.getOrderId());
    orderRes.setNum(orderReq.getNum());
    orderRes.setProductCode(orderReq.getProductCode());
    orderRes.setStatus("下单成功");

    return CommonResult.success(orderRes);


  }

}
